package org.syncsoft.overalt.gui.api;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * 
 * @author tptfc
 *
 */
public class WindowContextValue {
	private Map<String, Collection<Object>> values;

	{
		clear();
	}
	
	/**
	 * added a single value to key
	 * 
	 * @precondition	value and key are not null
	 * @postcondition	a single value with this key
	 * 					<strong>OBS:</strong> if exist a single or a collection of values
	 * 					with this key, the old values was deleted
	 * 
	 * @param key
	 * @param value
	 */
	public void addValue(String key, Object value) {
		if (key != null && value != null) {
			Collection<Object> values = new HashSet<Object>();
			values.add(value);
			getValues().put(key, values);
		}
	}
	
	/**
	 * added a value in a collection of values with some key
	 * 
	 * @precondition value and key are not null
	 * @postcondition a collection of values with some key that contains this value
	 * 
	 * @param key
	 * @param value
	 */
	public void addMultiValue(String key, Object value) {
		if (key != null && value != null) {
			Collection<Object> values = getValues().get(key);
			
			if (values == null) {
				values = new HashSet<Object>();
			}
			
			values.add(value);
			getValues().put(key, values);
		}
	}
	
	/**
	 * added a value a collection of values with some key
	 * 
	 * @precondition value and key are not null
	 * @postcondition a collection of values with some key that contains this value
	 * 
	 * @param key
	 * @param value
	 */
	public void addMultiValue(String key, Collection<Object> value) {
		if (key != null && value != null) {
			Collection<Object> values = getValues().get(key);
			
			if (values != null) {
				value.addAll(values);
			}
			
			getValues().put(key, value);
		}
	}
	
	@SuppressWarnings("unchecked")
	public void setValue(String key, Object value) {
		if (key != null) {
			Collection<Object> values;
			
			if (value instanceof Collection<?>) {
				values = (Collection) value;
			} else {
				values = new HashSet<Object>();
				values.add(value);
			}
			
			getValues().put(key, values);
		}
	}
	
	/**
	 * get a value by key
	 * @param key
	 * @return
	 */
	public <T> T getValue(String key) {
		T value = null;
		
		Collection<T> values = getValues(key);
		
		if (values != null) {
			for (T current : values) {
				value = current;
				break;
			}
		}
		
		return value;
	}
	
	/**
	 * get values by key
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> Collection<T> getValues(String key) {
		Collection<T> values;
		values = (Collection<T>) getValues().get(key);
		return values;
	}
	
	/**
	 * @postcondition deleted all values
	 */
	public void clear() {
		setValues(new HashMap<String, Collection<Object>>());
	}
	
	//	GETs AND SETs
	protected Map<String, Collection<Object>> getValues() {
		return values;
	}
	protected void setValues(Map<String, Collection<Object>> values) {
		this.values = values;
	}
}
